package com.android.ailaoshan.voice;

import android.content.Context;
import android.os.Environment;
import android.widget.Toast;

import com.android.ailaoshan.R;
import com.android.ailaoshan.index.MainActivity;
import com.android.ailaoshan.tools.BaseApplication;

import java.io.File;

import cafe.adriel.androidaudiorecorder.AndroidAudioRecorder;
import cafe.adriel.androidaudiorecorder.model.AudioChannel;
import cafe.adriel.androidaudiorecorder.model.AudioSampleRate;
import cafe.adriel.androidaudiorecorder.model.AudioSource;

public class StartVoice {

    private Context mContext;
    private MainActivity mainActivity;

    private BaseApplication baseApplication;

    /** 录音文件存储路径 */
    private final String VOICE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator +"AiLaoShan"+ File.separator + "Voice" +File.separator;

    public StartVoice(Context mContext, MainActivity mainActivity) {
        this.mContext = mContext;
        this.mainActivity = mainActivity;

        this.baseApplication = BaseApplication.getInstance();

        initRecorder();
    }

    /**
     * 录音初始化
     */
    private void initRecorder(){
        if(checkFile()){
            toRecorder();
        }else{
            Toast.makeText(mContext,"创建音频文件失败，请检查是否有存储权限",Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 开始录音
     */
    private void toRecorder(){
        String fileName = System.currentTimeMillis() + ".wav";
        // 文件名缓存
        this.baseApplication.setVoiceFile(fileName);

        String filePath = VOICE_PATH + fileName;
        int bgColor = mContext.getResources().getColor(R.color.voice_bg_color);

        AndroidAudioRecorder.with(this.mainActivity)
                .setFilePath(filePath)
                .setColor(bgColor)
                .setRequestCode(202)

                .setSource(AudioSource.MIC)
                .setChannel(AudioChannel.STEREO)
                .setSampleRate(AudioSampleRate.HZ_48000)
                .setAutoStart(false)
                .setKeepDisplayOn(true).record();
    }

    /**
     * 创建文件夹
     */
    private boolean checkFile(){
        // 检查存储文件夹是否存在，不存在则创建
        File folder = new File(VOICE_PATH);

        if(!folder.exists()){
            return folder.mkdirs();
        }else{
            return true;
        }
    }
}
